package me.zhengjie.service;

import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
@Service
public class MqttService {
    @Value("${mqtt.broker.url}")
    private String brokerUrl;

    @Value("${mqtt.broker.username}")
    private String userName;

    @Value("${mqtt.broker.password}")
    private String password;

    @Value("${mqtt.clientId}")
    private String clientId;

    @Value("${mqtt.topic}")
    private String topic;

    private MqttClient mqttClient;

    @PostConstruct
    public void init() {
        try {
            mqttClient = new MqttClient(brokerUrl, clientId);
            MqttConnectOptions connectOptions = new MqttConnectOptions();
            connectOptions.setUserName(userName);
            connectOptions.setPassword(password.toCharArray());
            mqttClient.setCallback(new MqttCallback() {
                public void connectionLost(Throwable throwable) {
                    //连接中断
                }

                public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                    //收到消息
                    System.out.println("msg=="+mqttMessage);
                }

                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    //发布完成
                }
            });
            mqttClient.connect(connectOptions);
            mqttClient.subscribe(topic);
        } catch (MqttException e) {
            //连接失败
        }
    }

    public void publishMessage(String topic, String message) {
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(0);
        try {
            mqttClient.publish(topic, mqttMessage);
        } catch (MqttException e) {
        }
    }
}
